package com.lzc.common;

import cn.hutool.core.lang.TypeReference;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.github.benmanes.caffeine.cache.Cache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class ImCache {

    @Autowired
    private Cache<String,String> cache;

    public void set(String key, String value){
        cache.put(key,value);
    }

    public String getString(String key){
        String value = cache.getIfPresent(key);
        return value;
    }

    public void set(String key, List list){
        String jsonStr = JSONUtil.toJsonStr(list);
        cache.put(key,jsonStr);
    }

    public List getList(String key){
        String listStr = cache.getIfPresent(key);
        if (StrUtil.isBlank(listStr)){
            return null;
        }
        JSONArray objects = JSONUtil.parseArray(listStr);
        List<Long> list = objects.toList(Long.class);
        return list;
    }

    // 删除key
    public void remove(String key) {
        cache.invalidate(key);
    }

    public static void main(String[] args) {
        List<Long> list = new ArrayList<>();
        list.add(1L);
        String jsonStr = JSONUtil.toJsonStr(list);
        System.out.println(jsonStr);
        JSONArray objects = JSONUtil.parseArray(jsonStr);
        List<Long> list1 = objects.toList(Long.class);
        System.out.println(list1);
    }
}
